﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Collections;


namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class MenuMobile : ClassManager.SessionManagerPage
    {
        private void GetAllParentMenu()
        {
            MenuParentsGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.GetMenuParents(null, null, null, 3);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            sdsMenuType.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString;

            if (!Page.IsPostBack)
            {
                //MenuDetailGrid.DataSource = new System.Data.DataTable();
                //MenuDetailGrid.DataBind();

            }
        }

        protected void MenuParentsGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                Telerik.Web.UI.GridEditableItem item = e.Item as Telerik.Web.UI.GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Menu menuEntity = ClassManager.InvokeEntityManager.Invoke_Menu_Entity(e);

                menuEntity.MenuId = int.Parse(Entity[GPSTrackingDBV2.Entities.MenuColumn.MenuId.ToString()].ToString());

                GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.DeleteParent(menuEntity.MenuId);

            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede eliminar la información.");
            }
        }

        protected void lbClearMenuFilters_Click(object sender, EventArgs e)
        {
            MenuParentsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in MenuParentsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
                else
                {
                    if (column is GridCheckBoxColumn)
                    {
                        GridCheckBoxColumn boundCheckColumn = column as GridCheckBoxColumn;
                        boundCheckColumn.CurrentFilterValue = "true";
                    }
                }
            }
            MenuParentsGrid.MasterTableView.Rebind();
            clearMenuDetailsGrid();
            ResizeGrid();
        }

        private void clearMenuDetailsGrid()
        {
            
        }

        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value);

            MenuParentsGrid.Height = Unit.Parse(Convert.ToString(Height));
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Menu...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Menu...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Menu...');", true);
        }

        protected void MenuParentsGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            GetAllParentMenu();
            ResizeGrid();
        }

        protected void MenuParentsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {

            int parentID = Convert.ToInt32(MenuParentsGrid.Items[MenuParentsGrid.SelectedItems[0].ItemIndex]["MenuId"].Text);

            ResizeGrid();
        }

        protected void MenuParentsGrid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                Telerik.Web.UI.GridEditableItem item = e.Item as Telerik.Web.UI.GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Menu menuEntity = ClassManager.InvokeEntityManager.Invoke_Menu_Entity(e);
                menuEntity.MenuTypeId = 3; //Aplicaciones
                menuEntity.TypeModuleId = 1;
                menuEntity.Name = Entity[GPSTrackingDBV2.Entities.MenuColumn.Name.ToString()].ToString();

                menuEntity.ToolTip = Entity[GPSTrackingDBV2.Entities.MenuColumn.ToolTip.ToString()].ToString();
                menuEntity.Page = Entity[GPSTrackingDBV2.Entities.MenuColumn.Page.ToString()].ToString();


                menuEntity.MenuId = GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.GetNextID();
                menuEntity.BySequence = Convert.ToInt16(MenuParentsGrid.Items.Count - 2);
                
                GPSTrackingDBV2.Data.DataRepository.MenuProvider.Insert(menuEntity);
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede insertar la información.");
            }

        }

        protected void MenuParentsGrid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                Telerik.Web.UI.GridEditableItem item = e.Item as Telerik.Web.UI.GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Menu menuEntity = ClassManager.InvokeEntityManager.Invoke_Menu_Entity(e);
                menuEntity.MenuTypeId = 3; //Aplicaciones
                menuEntity.TypeModuleId = 1;
                menuEntity.Name = Entity[GPSTrackingDBV2.Entities.MenuColumn.Name.ToString()].ToString();

                menuEntity.ToolTip = Entity[GPSTrackingDBV2.Entities.MenuColumn.ToolTip.ToString()].ToString();
                menuEntity.Page = Entity[GPSTrackingDBV2.Entities.MenuColumn.Page.ToString()].ToString();

                menuEntity.MenuId = int.Parse(Entity[GPSTrackingDBV2.Entities.MenuColumn.MenuId.ToString()].ToString());
                menuEntity.OriginalMenuId = menuEntity.MenuId;
                menuEntity.BySequence = Int16.Parse(Entity[GPSTrackingDBV2.Entities.MenuColumn.BySequence.ToString()].ToString());

                GPSTrackingDBV2.Data.DataRepository.MenuProvider.Update(menuEntity);
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede modificar la información.");
            }
        }

        protected void MenuParentsGrid_RowDrop(object sender, GridDragDropEventArgs e)
        {
            int menuID = Convert.ToInt32(e.DraggedItems[0]["MenuId"].Text);

            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.Menu> menuEntities = ConvertDataTableToEntities(GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.GetMenuParents(null, null, null, 3));

            GPSTrackingDBV2.Entities.Menu entityMenu = menuEntities.Find(x => x.MenuId == menuID);
            menuEntities.Remove(entityMenu);
            menuEntities.Insert(e.DestDataItem.ItemIndex, entityMenu);


            short orderNumber = 1;
            foreach (GPSTrackingDBV2.Entities.Menu entity in menuEntities)
            {
                entity.EntityState = GPSTrackingDBV2.Entities.EntityState.Changed;
                entity.BySequence = orderNumber;
                entity.OriginalMenuId = entity.MenuId;
                orderNumber++;
            }

            GPSTrackingDBV2.Data.DataRepository.MenuProvider.Update(menuEntities);

            MenuParentsGrid.DataSource = menuEntities;
            MenuParentsGrid.DataBind();
        }

        protected GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.Menu> ConvertDataTableToEntities(System.Data.DataTable dt)
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.Menu> entities = new GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.Menu>();
            foreach (System.Data.DataRow row in dt.Rows)
            {
                GPSTrackingDBV2.Entities.Menu entity = new GPSTrackingDBV2.Entities.Menu();

                entity.MenuId = Convert.ToInt32(row[GPSTrackingDBV2.Entities.MenuColumn.MenuId.ToString()]);
                entity.Name = Convert.ToString(row[GPSTrackingDBV2.Entities.MenuColumn.Name.ToString()]);
                entity.Parent = row[GPSTrackingDBV2.Entities.MenuColumn.Parent.ToString()] == System.DBNull.Value ? new int?() : Convert.ToInt32(row[GPSTrackingDBV2.Entities.MenuColumn.Parent.ToString()]);
                entity.ToolTip = Convert.ToString(row[GPSTrackingDBV2.Entities.MenuColumn.ToolTip.ToString()]);
                entity.Page = Convert.ToString(row[GPSTrackingDBV2.Entities.MenuColumn.Page.ToString()]);
                entity.IsVisibleMaster = Convert.ToBoolean(row[GPSTrackingDBV2.Entities.MenuColumn.IsVisibleMaster.ToString()]);
                entity.IsVisibleAdministrator = Convert.ToBoolean(row[GPSTrackingDBV2.Entities.MenuColumn.IsVisibleAdministrator.ToString()]);
                entity.IsVisibleUser = Convert.ToBoolean(row[GPSTrackingDBV2.Entities.MenuColumn.IsVisibleUser.ToString()]);
                entity.ImageUrl = Convert.ToString(row[GPSTrackingDBV2.Entities.MenuColumn.ImageUrl.ToString()]);
                entity.Width = row[GPSTrackingDBV2.Entities.MenuColumn.Width.ToString()] == System.DBNull.Value ? new short?() : Convert.ToInt16(row[GPSTrackingDBV2.Entities.MenuColumn.Width.ToString()]);
                entity.Heigth = row[GPSTrackingDBV2.Entities.MenuColumn.Heigth.ToString()] == System.DBNull.Value ? new short?() : Convert.ToInt16(row[GPSTrackingDBV2.Entities.MenuColumn.Heigth.ToString()]);
                entity.Positionx = row[GPSTrackingDBV2.Entities.MenuColumn.Positionx.ToString()] == System.DBNull.Value ? new short?() : Convert.ToInt16(row[GPSTrackingDBV2.Entities.MenuColumn.Positionx.ToString()]);
                entity.Positiony = row[GPSTrackingDBV2.Entities.MenuColumn.Positiony.ToString()] == System.DBNull.Value ? new short?() : Convert.ToInt16(row[GPSTrackingDBV2.Entities.MenuColumn.Positiony.ToString()]);
                entity.MenuTypeId = Convert.ToInt32(row[GPSTrackingDBV2.Entities.MenuColumn.MenuTypeId.ToString()]);
                entity.TypeModuleId = Convert.ToInt32(row[GPSTrackingDBV2.Entities.MenuColumn.TypeModuleId.ToString()]);
                entity.BySequence = Convert.ToInt16(row[GPSTrackingDBV2.Entities.MenuColumn.BySequence.ToString()]);

                entities.Add(entity);
            }

            return entities;
        }
        
    }
}